package com.yuanqi.Controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yuanqi.Common.Pojo.Vo.ChatVo;
import com.yuanqi.Common.Pojo.entity.Chat;
import com.yuanqi.Common.config.ThreadLocalConfig;
import com.yuanqi.Return.Result;
import com.yuanqi.Service.ChatService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/v1/chat")
public class ChatController {

    @Resource
    ChatService chatService;
    @Resource
    ThreadLocalConfig threadLocalConfig;
    /**
     * 绑定用户Id和webSocket里面的Id
     * @return
     */
    @PostMapping("/bindUser")
    public Result bindUser(@RequestBody ChatVo chatVo){
        chatService.bindUser(chatVo);
        return Result.success("绑定成功");
    }

    /**
     * 获取用户未上线时的信息
     * @return
     */
    @PostMapping("/getUnreadMsg")
    public Result getUnreadMsg(){
        ArrayList<Object> objects = new ArrayList<>();
        Long userId = Long.valueOf(
                threadLocalConfig.get().get("userId").toString()

        );
        LambdaQueryWrapper<Chat> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Chat::getReaded,1);
        wrapper.eq(Chat::getToId,userId);
        List<Chat> list = chatService.list(wrapper);
        list.forEach(v->{
            v.setReaded(0);
            chatService.update(v,new LambdaQueryWrapper<Chat>().eq(Chat::getId,v.getId()));
        });
        return Result.success(list);
    }

    /**
     * 发送信息
     * @return
     */
    @PostMapping("/sendMsg")
    public  Result sendMsg(@RequestBody Chat chat){
        chatService.sendMsg(chat);
        return Result.success("发送cg");
    }
}
